<?php
/**
 * Created by .
 * User: luogan
 * Date: 2022/1/13
 */

namespace app\admin\service;


use app\exception\ErrorException;
use app\model\AdminLoginLogModel;
use app\model\AdminModel;
use ipip\datx\City;
use Jenssegers\Agent\Agent;
use think\facade\Db;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Param;
class AdminService extends BaseService
{

    /**
     * 用户登录
     * @Returned("token", type="string", desc="toekn令牌")
     * @Returned("admin", type="object",desc="管理员信息",ref="app\model\AdminModel\getAdmin")
     */
    public function login($username,$password)
    {
        $admin =AdminModel::where('username', $username)->find();
        if (!$admin) {
            throw new ErrorException('账户不存在');
        }
        if ($admin['status'] == 1) {
            throw new ErrorException('账户已禁用');
        }
        $pwd = md5($admin['salt'] . $password);
        if (!hash_equals($admin['password'], $pwd)) {
            throw new ErrorException('账号或密码错误');
        }
        $data['last_login_time'] = time();
        $data['last_login_ip'] = get_client_ip();
        $this->adminLoginLog($admin['id'],$admin['username'],$data['last_login_ip']);
        Db::startTrans();
        try{
            $admin->allowField(['last_login_time', 'last_login_ip'])->save($data);
            //登录记录
            $this->adminLoginLog($admin['id'],$admin['username'],$data['last_login_ip']);
            Db::commit();
        } catch(\Exception $e){
            Db::rollback();
            throw new ErrorException('登录失败');
        }
        $payload = [
            'admin_id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'head_pic' => $admin['head_pic'],
            'role'     => $admin['role'],
            'dept_id'     => $admin['dept_id'],
        ];
        //生成token
        $strToken = (new TokenService())->signToken($payload);
        //生成菜单权限缓存
        $menu = (new AuthMenuService())->init($admin['id']);
        return ['token' => $strToken,'admin' => $admin,'menu'=>$menu];
    }

    /**
     * 管理员退出
     * @return bool
     */
    public function logout()
    {
        $adminId = admin_id();
        $result = (new TokenService())->delToken($adminId);
        if (!$result){
            throw new ErrorException();
        }
        return $result;
    }

    /**
     * 管理员列表
     */
    public function getList($data)
    {
        $result = (new AdminModel)
            ->withSearch($this->searchFields($data),$this->searchData($data))
            ->paginate($this->getLimit($data));
        if (!$result){
            throw new ErrorException();
        }
        return $result;
    }

    /**
     * 管理员新增
     */
    public function create($data)
    {
        $data['salt'] = get_rand_char();
        $data['password'] =  md5($data['salt'] . $data['password']);
        $result = AdminModel::create($data);
        if (!$result){
            throw new ErrorException();
        }
        admin_log('新增管理员：'.$data['username'].' 管理员id '.$result);
        return $result;
    }

    /**
     * 管理员编辑
     */
    public function update($data)
    {
        if (isset($data['password'])){
            $data['salt'] = get_rand_char();
            $data['password'] =  md5($data['salt'] . $data['password']);
        }
        $result = AdminModel::where('id',$data['id'])->update($data);
        if (!$result){
            throw new ErrorException();
        }
        admin_log('编辑管理员：管理员id '.$data['id']);
        return $result;
    }

    /**
     * 获取管理员详情
     */
    public function getInfo($id)
    {
        $result = AdminModel::find($id);
        if (!$result){
            throw new ErrorException();
        }
        return $result;
    }

    /**
     * 删除管理员
     */
    public function delete($id)
    {
        $result = AdminModel::destroy($id);
        if (!$result){
            throw new ErrorException();
        }
        return $result;
        admin_log('删除管理员：管理员id '.$data['id']);
    }


    /**
     * 生成登录记录
     * @param $adminId
     * @param $username
     * @param $ip
     * @param $remark
     */
    public function adminLoginLog($adminId,$username,$ip,$remark='登录成功')
    {
        $agent = new Agent();
        $user_agent = request()->header('user-agent');
        $agent->setUserAgent($user_agent[0]);
        $agent->is('Windows');
        //获取浏览器
        $browser = $agent->browser();
        //获取浏览器版本
        $browser_version = intval($agent->version($browser));
        //获取操作系统
        $platform = $agent->platform();
        //获取操作系统版本
        $platform_version = intval($agent->version($platform));
        // 城市级数据库
        $bs =  new City(public_path('ipdata').'17monipdb.datx');
        $address = $bs->find($ip);
        $reg['ip_province'] = isset($address[1]) ? $address[1] : '';
        $reg['ip_city'] = isset($address[2]) ? $address[2] : '';
        $reg['ip_address'] = implode(" ", $address);
        $region = $reg['ip_province'] . ' ' . $reg['ip_city'] . ' ' . $reg['ip_address'];
        $log = AdminLoginLogModel::create([
            'admin_id' => $adminId,
            'username' => $username,
            'ip' =>$ip,
            'browser' => $browser . ' ' . $browser_version,
            'system' => $platform . ' ' . $platform_version,
            'region' => $region,
            'remark' =>$remark,
        ]);
        return $log;
    }

}
